package com.joker.controller;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/Socket/{username}")
public class Websocket {

    //在线人数
    private static int onlinesum = 0;
    //在线用户
    private static Map<String,Websocket> clients=new ConcurrentHashMap<String,Websocket>();

    private Session session;
    private String username;

    @OnOpen
    public void OnOpen(@PathParam("username") String username, Session session) throws IOException {
        this.username=username;
        this.session=session;
        addOnlinesum();
        clients.put(username,this);
        System.out.println("有用户上线");
    }

    @OnClose
    public void OnClose() throws IOException{
        clients.remove(this.username);
        subOnlinesum();
        System.out.println("有用户下线");
    }

    @OnMessage
    public void OnMessage(String message,Session session){
        System.out.println(message);
    }
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    public static synchronized void addOnlinesum(){
        Websocket.onlinesum++;
    }
    public static synchronized void subOnlinesum(){
        Websocket.onlinesum--;
    }

    public static synchronized Map<String, Websocket> getClients(){
        return clients;
    }

}
